<?php
namespace App\Services;

use App\AccessToken;
use App\Lib\Util\StringUtil;
use DB;
use Carbon\Carbon;

class AccessTokenService
{
    public function getAccessToken($userId, $appId)
    {
        $accessToken = AccessToken::where('user_id', $userId)
            ->where('app_id', $appId)->first();

        return $accessToken;
    }

    public function isTokenExists($userId, $appId)
    {
        return null !== $this->getAccessToken($userId, $appId);
    }

    public function createBackstageAccessToken($userId, $appId, $ip, $flashToken = true)
    {
        $accessToken = $this->getAccessToken($userId, $appId);

        if (isset($accessToken)) {
            $accessToken->last_updated_time = Carbon::now();
            $accessToken->device_ip_addr = $ip;
            if ($flashToken) {
                $accessToken->access_token = StringUtil::guid();
            }

            AccessToken::where('user_id', $userId)
                ->where('app_id', $appId)->update($accessToken->toArray());
        } else {
            $accessToken = AccessToken::create([
                'user_id' => $userId,
                'app_id'  => $appId,
                'client_type' => AccessToken::$CLIENT_TYPE_WEB,
                'device_ip_addr' => $ip,
                'access_token' => StringUtil::guid(),
                'last_updated_time' => Carbon::now(),
            ]);
        }

        return $accessToken;
    }

    public function isTokenValid($userId, $appId, $token, $ip)
    {
        if ($this->isTokenExists($userId, $appId)) {
            $accessToken = $this->getAccessToken($userId, $appId);
            if ($accessToken->access_token == $token) {
                $expired = $this->isTokenExpired($userId, $appId);

                if (!$expired) {
                    $this->createBackstageAccessToken($userId, $appId, $ip, false);
                    return true;
                }
            }
        }

        return false;
    }

    public function isTokenExpired($userId, $appId)
    {
        $accessToken = $this->getAccessToken($userId, $appId);

        if (Carbon::now()->diffInSeconds(Carbon::parse($accessToken->last_updated_time)) < 7200) {
            return false;
        }

        return true;
    }
}
